package com.boomsecret.concurrent;

import java.util.concurrent.CountDownLatch;

/**
 * Created by wangjinliang on 2018/1/23.
 */
public class CountDownLatchDemo {
    private static final int TEACHER_COUNT = 1;
    private static final int STUDENT_COUNT = 5;

    public static void main(String[] args) {
        CountDownLatch teacher = new CountDownLatch(TEACHER_COUNT);
        CountDownLatch students = new CountDownLatch(STUDENT_COUNT);

        // 学生入场
        for (int index = 0; index < STUDENT_COUNT; index ++) {
            new Thread(new Test(teacher, students)).start();
        }

        System.out.println("发试卷");

        try {
            teacher.countDown();    // 老师说答题开始
            students.await();   // 等待学生做完题目
            System.out.println("所有学生都已经完成答题");
            System.out.println("考试结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}

class Test implements Runnable {
    private CountDownLatch teacher;
    private CountDownLatch students;

    public Test(CountDownLatch teacher, CountDownLatch students) {
        this.teacher = teacher;
        this.students = students;
    }

    @Override
    public void run() {
        try {
            this.teacher.await();
            answer();
            this.students.countDown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void answer() throws Exception {
        Thread.sleep(1000);
        System.out.println("在紧张答题中 ThreadId:" + Thread.currentThread().getId());
    }
}
